<?php

/**
 * 人人红娘
 */
class hn
{
    public $educationMap = [1 => '大专以下', 2 => '大专', 3 => '本科', 4 => '硕士', 5 => '博士'];
    public $jobMap = [1 => '计算机/互联网/通信', 2 => '公务员/事业单位', 3 => '教师', 4 => '医生', 5 => '护士', 6 => '空乘人员',
        7 => '生产/工艺/制造', 8 => '商业/服务业/个体经营', 9 => '金融/银行/投资/保险', 10 => '文化/广告/传媒', 11 => '娱乐/艺术/表演', 12 => '律师/法务',
        13 => '教育/培训/管理咨询', 14 => '建筑/房地产/物业', 15 => '酒店/旅游', 16 => '农业', 17 => '在校学生'];
    public $religionMap = [0 => '无宗教信仰', 1 => '佛教', 2 => '道教', 3 => '基督教', 4 => '伊斯兰教', 5 => '其他'];
    public $constellationMap = [1 => '摩羯', 2 => '水瓶', 3 => '双鱼', 4 => '白羊', 5 => '金牛', 6 => '双子', 7 => '巨蟹', 8 => '狮子', 9 => '处女', 10 => '天秤', 11 => '天蝎', 12 => '射手'];
    public $shengxiaoMap = [1 => '鼠', 2 => '牛', 3 => '虎', 4 => '兔', 5 => '龙', 6 => '蛇', 7 => '马', 8 => '羊', 9 => '猴', 10 => '鸡', 11 => '狗', 12 => '猪'];
    public $maritalMap = [1 => '未婚', 2 => '离异无子女', 3 => '离异不带子女', 4 => '离异带子女', 5 => '丧偶无子女', 6 => '丧偶有子女'];
    public $c_maritalMap = [1 => '未婚', 2 => '离异或丧偶'];
    public $c_educationMap = [2 => '大专及以上', 3 => '本科及以上', 4 => '硕士及以上', 5 => '博士及以上'];

    //首页 全局数据变量放这里输出。
    public function getIndex()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $reg = M('hongniang_referee')->where(['uid' => $user['id']])->find();
        $check = M('hongniang_love')->where(['uid' => $user['id']])->find();
        $matchmakerModel = M('hongniang_matchmaker')->where(['uid' => $user['id']])->find();
        if (!$matchmakerModel['id']) {
            $referee = $reg;
            if ($referee['parentId']) {
                $referee2 = M('hongniang_referee')->where(['uid' => $referee['parentId']])->find();
            }
            $initData = [
                'uid' => $user['id'],
                'openId' => $openId,
                'refereeId' => $referee['parentId'] ?: 0,
                'refereeId2' => $referee2['parentId'] ?: 0,
                'createTime' => date('Y-m-d H:i:s'),
                'earning' => 0,
                'balance' => 0,
                'offer' => 0,
                'offerLoves' => 0,
                'qrcode' => ''
            ];
            $result = M('hongniang_matchmaker')->add($initData);
            $initData['id'] = $result;
            $initData['nickName'] = $user['nickname'];
            $initData['headimgurl'] = $user['headimgurl'];
            $matchmakerModel = $result ? $initData : [];
            if (!$reg) {
                M('hongniang_referee')->add(['uid' => $user['id'], 'parentId' => $initData['refereeId'], 'reg' => 0]);
            }
        } else {
            $matchmakerModel['nickName'] = $user['nickname'];
            $matchmakerModel['headimgurl'] = $user['headimgurl'];
        }
        if ($reg['reg']) {
            foreach ($check as $k => $item) {
                $check[$k] = !in_array($k, ['verify', 'vip', 'success', 'house', 'car', 'religion']) ? ($item ?: null) : $item;
            }
            $check['nickName'] = $user['nickname'];
            $check['headimgurl'] = $user['headimgurl'];
            $check['photo'] = @json_decode($check['photo'], true);
            $check['age'] = $check['birthday'] ? (date('Y') - date('Y', strtotime($check['birthday']))) : null;
            $check['isBase'] = 1;
            $check['isAgent'] = $check['agent'];
            $condition = M('hongniang_condition')->where(['uid' => $user['id']])->find();
            $check['isCondition'] = $condition ? 1 : 0;
            if ($condition) {
                foreach ($condition as $k => $v) {
                    $condition[$k] = $v ?: null;
                }
                $condition['showMinAge'] = $condition['maxAge'] ? (date('Y') - $condition['maxAge']) : null;
                $condition['showMaxAge'] = $condition['minAge'] ? (date('Y') - $condition['minAge']) : null;
            }
            Output::instance()->module('hn', "index")->object(['userInfo' => $check, 'conditionInfo' => $condition, 'matchmaker' => $matchmakerModel]);
        } else {
            Output::instance()->module('hn', "index")->object(['userInfo' => ['isBase' => 0, 'isAgent' => 0, 'isCondition' => 0, 'matchmaker' => $matchmakerModel], 'conditionInfo' => []]);
        }
    }

    public function getAgreement($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        Session::switchCustomer(0);
        $model = M("hongniang_config");
        $result = $model->where(['pk' => 'agreement'])->find();
        if ($result) {
            Output::instance()->module('hn', "agreement")->object(['content' => htmlspecialchars_decode($result['value'])]);
        } else {
            Output::instance()->resultCode(1, '协议未设置');
        }
    }

    public function regLover($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $refereeModel = M('hongniang_referee')->where(['uid' => $user['id']])->find();
        $refereeId = $refereeModel ? $refereeModel['parentId'] : (intval($params->refereeId) ?: 0);
        $loveModel = M('hongniang_love');
        if ($refereeId === intval($user['id'])) {
            Output::instance()->resultCode(false, '不能给自己做红娘哦');
            return;
        }
        $refereeId2 = 0;
        if ($refereeId) {
            $d = M('hongniang_referee')->where(['uid' => $refereeId])->find();
            $refereeId2 = $d['parentId'] ?: 0;
        }
        $data = [
            'uid' => $user['id'],
            'openId' => $openId,
            'weixin' => $params->weixin,//上传后的微信图片地址
            'realname' => trim($params->realname),//真实姓名
            'gender' => intval($params->gender),//性别
            'birthday' => date('Y-m-d', strtotime($params->birthday)),//生日
            'height' => intval($params->height),//身高cm
            'education' => intval($params->education),//学历
            'job' => intval($params->job),//职业
            'phone' => $params->phone,//手机号码
            'earning' => intval($params->earning),//年收入 万元
            'province' => trim($params->province),//地区省
            'city' => trim($params->city),
            'marital' => intval($params->marital),//婚姻状况
            'onlyChild' => intval($params->onlyChild),//是否独生子女  1=独生子女，2=非独生子女
            'house' => intval($params->house),//是否有房
            'car' => intval($params->car),//是否有车
            'religion' => intval($params->religion),//宗教信仰
            'registerProvince' => trim($params->registerProvince),//户口所在地(省)
            'registerCity' => trim($params->registerCity),//户口所在地(省)
            'nation' => trim($params->nation),//民族
            'weight' => intval($params->weight),//体重 kg
            'constellation' => intval($params->constellation),//星座
            'shengxiao' => $params->shengxiao ?: '',//生肖（属相）
            'card_front' => $params->card_front ?: '',//身份证正面
            'card_con' => $params->card_con ?: '',//身份证反面
            'hukou_front' => $params->hukou_front ?: '',//户口主页
            'hukou_con' => $params->hukou_con ?: '',//户口个人页
            'education_pic' => $params->education_pic ?: '',//教育证明
            'job_pic' => $params->job_pic ?: '',//工作证明
            'house_pic' => $params->house_pic ?: '',//房产证明
            'car_pic' => $params->car_pic ?: ''//有车证明
        ];

        $check = $loveModel->where(['uid' => $user['id']])->find();
        if ($check) {
            if ($check['verify'] || $check['vip']) {
                Output::instance()->resultCode(true, '您的资料已审核，不能修改');
                return;
            }
            function pass($v)
            {
                return $v === '' ? false : true;
            }

            $data = array_filter($data, "pass");

            $loveResult = $loveModel->where(['uid' => $user['id']])->save($data);
            if ($loveResult) {
                M('hongniang_referee')->where(['uid' => $user['id']])->save(['reg' => 1]);

                Output::instance()->resultCode(true, '更新成功');
            } else {
                Output::instance()->resultCode(true, '更新完成');
            }
        } else {
            $data['photo'] = json_encode([]);
            $data['verify'] = 0;
            $data['agent'] = 0;
            $data['vip'] = 0;
            $data['loveId'] = 0;
            $data['success'] = 0;
            $data['love'] = 0;
            $data['loveEach'] = 0;
            $data['recharge'] = 0;
            $data['surplus'] = 0;
            $data['matchmakerId'] = $refereeId;//红娘
            $data['refereeId'] = $refereeId;//推荐人
            $data['refereeId2'] = $refereeId2;
            $data['createTime'] = date('Y-m-d H:i:s', time());

            //执行默认代理商选择（根据所选地区）
            if ($data['city']) {
                $agentModel = M('hongniang_agent');
                $where['status'] = 1;
                $where['city'] = $data['city'];
                $list = $agentModel->where($where)->select();
                if ($list) {
                    $data['agent'] = $list[0]['id'] ?: 0;
                }
            }


            $loveResult = $loveModel->add($data);
            if ($loveResult) {
                if ($refereeModel) {
                    M('hongniang_referee')->where(['uid' => $user['id'], 'parentId' => $refereeId])->save(['reg' => 1]);
                } else {
                    M('hongniang_referee')->add(['uid' => $user['id'], 'parentId' => $refereeId, 'reg' => 1]);
                }

                if ($refereeId) {
                    M('hongniang_matchmaker')->where(['uid' => $refereeId])->setInc('offer', 1);
                    M('hongniang_matchmaker')->where(['uid' => $refereeId])->setInc('offerLoves', 1);
                }
                if ($refereeId2) {
                    M('hongniang_matchmaker')->where(['uid' => $refereeId2])->setInc('offer', 1);
                    M('hongniang_matchmaker')->where(['uid' => $refereeId2])->setInc('offerLoves', 1);
                }
                Output::instance()->resultCode(true, '注册成功');
            } else {
                Output::instance()->resultCode(false, '注册失败');
            }
        }
    }

    public function regCondition($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }

        $params->cmaxAge ? $minYear = date('Y') - intval($params->cmaxAge) : $minYear = 0;
        $params->cminAge ? $maxYear = date('Y') - intval($params->cminAge) : $maxYear = 0;

        $conditionModel = M('hongniang_condition');

        $conditionData = [
            'uid' => $user['id'],
            'openId' => $openId,
            'minAge' => $minYear,
            'maxAge' => $maxYear,
            'minHeight' => intval($params->cminHeight),
            'maxHeight' => intval($params->cmaxHeight),
            'minWeight' => intval($params->cminWeight),
            'maxWeight' => intval($params->cmaxWeight),
            'education' => intval($params->ceducation),
            'minEarning' => intval($params->cminEarning),
            'maxEarning' => intval($params->cmaxEarning),
            'province' => trim($params->cprovince),
            'city' => trim($params->ccity),
            'marital' => intval($params->cmarital)
        ];
        $check = $conditionModel->where(['uid' => $user['id']])->find();
        if ($check) {
            $conditionResult = $conditionModel->where(['uid' => $user['id']])->save($conditionData);
        } else {
            $conditionResult = $conditionModel->add($conditionData);
        }
        Output::instance()->resultCode(0, '写入成功');
    }

    public function getAgentList($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        Session::switchCustomer(0);
        $model = M('hongniang_agent');
        $where['status'] = 1;
        if ($params->city) {//&params={"city":"南京市"}，不传城市将返回所有验证点
            $where['city'] = $params->city;
        }
        $list = $model->where($where)->select();
        if ($list) {
            Output::instance()->module('hn', "agentList")->object($list);
        } else {
            Output::instance()->module('hn', "agentList")->object([]);
        }
    }

    /*
     * @id 代理商ID
     */
    public function setAgent($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $row = M('hongniang_agent')->where(['id' => $params->id])->find();

        if ($row) {
            $model = M('hongniang_love');

            $result = $model->where(['uid' => $user['id']])->save(['agent' => $params->id]);
            if ($result) {
                Output::instance()->resultCode(0, '写入成功');
            } else {
                Output::instance()->resultCode(1, '写入失败');
            }
        } else {
            Output::instance()->resultCode(1, '代理商不存在');
        }

    }

    /*
     * 个人中心-基本资料
     */
    public function centerBase($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $info = M('hongniang_love')->where(['uid' => $user['id']])->find();
        $matchmakerModel = M('hongniang_matchmaker')->where(['uid' => $user['id']])->find();
        if (!$matchmakerModel['id']) {
            $referee = M('hongniang_referee')->where(['uid' => $user['id']])->find();
            if ($referee['parentId']) {
                $referee2 = M('hongniang_referee')->where(['uid' => $referee['parentId']])->find();
            }
            $initData = [
                'uid' => $user['id'],
                'openId' => $openId,
                'refereeId' => $referee['parentId'] ?: 0,
                'refereeId2' => $referee2['parentId'] ?: 0,
                'createTime' => date('Y-m-d H:i:s'),
                'earning' => 0,
                'balance' => 0,
                'offer' => 0,
                'offerLoves' => 0,
                'qrcode' => ''
            ];
            $result = M('hongniang_matchmaker')->add($initData);
            $initData['id'] = $result;
            $initData['nickName'] = $user['nickname'];
            $initData['headimgurl'] = $user['headimgurl'];
            $matchmakerModel = $result ? $initData : [];
            if (!$referee) {
                M('hongniang_referee')->add(['uid' => $user['id'], 'parentId' => $initData['refereeId'], 'reg' => 0]);
            }
        } else {
            $matchmakerModel['nickName'] = $user['nickname'];
            $matchmakerModel['headimgurl'] = $user['headimgurl'];
        }
        if ($info) {
            $info['nickName'] = $user['nickname'];
            $info['headimgurl'] = $user['headimgurl'];
            $info['photo'] = @json_decode($info['photo'], true);
            $info['age'] = date('Y') - date('Y', strtotime($info['birthday']));
            $info['matchmaker'] = $matchmakerModel;
            Output::instance()->module('hn', "center")->object($info);
        } else {
            $info['matchmaker'] = $matchmakerModel;
            Output::instance()->module('hn', "center")->object($info);
        }
    }

    /*
     * 个人中心-我的账户
     * 说明：页面中的剩余次数在基本资料的surplus字段中
     */
    public function centerAccount($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }

        $start = $params->start ?: 0;
        $limit = $params->limit ?: 10;

        $info = M('hongniang_quota')->where(['uid' => $user['id']])->limit($start, $limit)->select();
        $count = M('hongniang_quota')->where(['uid' => $user['id']])->count();
        if ($info) {
            Output::instance()->module('hn', "center")->objArray($info, $count);
        } else {
            Output::instance()->resultCode(99, '没有充值记录');
        }
    }

    /*
     * 个人中心-我的二维码
     *
     */
    public function centerQrcode($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $matchmaker = M('hongniang_matchmaker')->where(['uid' => $user['id']])->find();
        $echoImg = $matchmaker['qrimg'];
        $qrImg = $matchmaker['qrcode'];

        if (!$echoImg) {
            $raw = M('hongniang_config')->where(['pk' => ['in', ['position', 'background']]])->select();
            if (!$matchmaker['qrcode']) {
                $data = QRCode::add(
                    '红娘',
                    "QRCODE_$user[id]" . time(),
                    "hn", $user['id'], "myInvited",
                    "QR_LIMIT_STR_SCENE", '', '', $cid
                );
                $qrImg = $data["img"];
                M('hongniang_matchmaker')->where(['uid' => $user['id']])->save(['qrcode' => $qrImg]);
            }
            if (!$qrImg) {
                return;
            }

            foreach ($raw as $row) {
                if ($row['pk'] == 'position') {
                    $position = json_decode($row['value'], true);
                }
                if ($row['pk'] == 'background') {
                    $backImg = $row['value'];
                }
            }
            $fileName = time() . $openId;
            $out = self::createImage($fileName, $qrImg, $backImg, $position['x'] . '|' . $position['y'], $position['w'] . '*' . $position['h']);
            if ($out && !$out->code) {
                $updateData["qrimg"] = $out->path;
                $updateData['qrcode'] = $qrImg;
                M('hongniang_matchmaker')->where(['uid' => $user['id']])->save($updateData);
                Output::instance()->module('hn', "center")->object(['qrcode' => $out->path]);
            } else {
                Output::instance()->resultCode(1, $out->msg);
                return;
            }
        } else {
            $result['qrcode'] = $echoImg;
            Output::instance()->module('hn', "center")->object($result);
        }


    }

    public function createImage($fileName, $qrImg, $bgImgUrl, $location, $size)
    {
        $fname = "vendor_$fileName.png";
        $fileName = LOCAL_PIC_PATH . "/$fname";

        $img = self::curls($bgImgUrl);

        $img = imagecreatefromstring($img);
        if (!$img) {
            $out1 = new stdClass();
            $out1->code = 1;
            $out1->msg = "背景图片获取错误，请重试";
            return $out1;
        }
        $imgWidth = imagesx($img);
        $imgHeight = imagesy($img);
        $qrImg = self::curls($qrImg);
        $qrImg = imagecreatefromstring($qrImg);
        if (!$qrImg) {
            $out1 = new StdClass();
            $out1->code = 1;
            $out1->msg = "二维码生成错误，请重试";
            return $out1;
        }
        $qrImgWidth = imagesx($qrImg);
        $qrImgHeight = imagesy($qrImg);
        if ($size) {
            $size = explode("*", $size);
            $sizeW = $size[0];
            $sizeH = $size[1];
        } else {
            $sizeW = 220;
            $sizeH = 220;
        }
        if ($location) {
            $location = explode("|", $location);
            $qrImgLeft = $location[0];
            $qrImgTop = $location[1];
        } else {
            $qrImgLeft = $imgWidth / 2 - 110;
            $qrImgTop = $imgHeight / 2 - 110;
        }
        imagecopyresampled($img, $qrImg, $qrImgLeft, $qrImgTop, 0, 0, $sizeW, $sizeH, $qrImgWidth, $qrImgHeight);
        imagejpeg($img, $fileName);
        imagedestroy($img);

        //开始上传
        if ($qrImg) {
            if (file_exists($fileName)) {
                $out = R("Upload/uploadLocalFileToOss", array($fname, $fileName));
                if (!$out->code) {
                    return $out;
                }
            }
        } else {
            $out = new StdClass();
            $out->code = 1;
            return $out;
        }
    }

    public function curls($url, $timeout = '10')
    {
        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 3. 执行并获取HTML文档内容
        $info = curl_exec($ch);
        // 4. 释放curl句柄
        curl_close($ch);

        return $info;
    }

    public function myInvited($params)
    {
        $message = $params->message;
        $cid = Session::$user["customerId"];
        $openId = $message->fromUserName;
        Session::switchCustomer(0);
        $hnReferee = M('hongniang_referee');
        $hnMatchmaker = M('hongniang_matchmaker');
        $love = M('hongniang_love');
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        $templateModel = M('template_messages');
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $isReg = $love->where(['uid' => $user['id']])->find();
        if ($isReg['id']) {
            return;
        }

        if ($params->id) {
            $check = $hnReferee->where(['uid' => $user['id']])->find();
            $invitedPerson = $userModel->where(['id' => $params->id])->find();
            if ($invitedPerson['id'] === $user['id']) {
//                Output::instance()->resultCode(1, '不能推荐自己哦');
                return;
            }
            if (!$check) {
                // TODO: 封装发送模板消息的模板2017-04-27
                $hnReferee->add(['uid' => $user['id'], 'parentId' => $params->id, 'reg' => 0]);
                $hnMatchmaker->where(['uid' => $params->id])->setInc('offer', 1);
                //发送模板消息
                $templatemsg = $templateModel->where(['status' => 'hnQrcodeInvited'])->find();
                $data['first'] = array('value' => '一起做红娘新会员关注成功', 'color' => "#743A3A");
                $data['keyword1'] = array('value' => $invitedPerson['nickname'], 'color' => '#173177');
                $data['keyword2'] = array('value' => $user['nickname'], 'color' => '#173177');
                $data['remark'] = array('value' => '', "color" => '#008000');
                $template_id = $templatemsg['templateId'];
                $url = '';//链接
                $toUser = $invitedPerson['openid'];//发送给谁（微信的openid）
                $topcolor = "#FF0000";
                WeixinApi::sendTpl($toUser, $template_id, $url, $topcolor, $data);
                //结束
            }
        }
    }

    /*
     * 设置我的照片
     *@params ["http://img.com/b.jpg","http://img.com/a.jpg"]
     */
    public function setPhoto($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        if (is_array($params)) {
            $old = M('hongniang_love')->where(['uid' => $user['id']])->find();
            $oldPhoto = @json_decode($old['photo'], true);
            $result = array_unique(array_merge((array)$oldPhoto, $params));
            $return = M('hongniang_love')->where(['uid' => $user['id']])->save(['photo' => json_encode($result)]);
            if ($return) {
                Output::instance()->resultCode(0, '上传成功');
            } else {
                Output::instance()->resultCode(0, '上传完成');
            }
        } else {
            Output::instance()->resultCode(99, "格式错误");
        }
    }

    /*
     * 删除我的照片
     *@params ["http://img.com/b.jpg","http://img.com/a.jpg"]
     */
    public function delPhoto($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        if (is_array($params)) {
            $old = M('hongniang_love')->where(['uid' => $user['id']])->find();
            $oldPhoto = @json_decode($old['photo'], true);

            $result = array_diff((array)$oldPhoto, $params);
            $result = array_values($result);

            $return = M('hongniang_love')->where(['uid' => $user['id']])->save(['photo' => json_encode($result)]);
            if ($return) {
                Output::instance()->resultCode(0, '上传成功');
            } else {
                Output::instance()->resultCode(0, '上传完成');
            }
        } else {
            Output::instance()->resultCode(99, "格式错误");
        }
    }

    /*
     *关注我的人
     */
    public function loveMe($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }

        $start = $params->start ?: 0;
        $limit = $params->limit ?: 10;

        $data = M('hongniang_love_info')->where(['toUid' => $user['id']])->limit($start, $limit)->select();
        $count = M('hongniang_love_info')->where(['toUid' => $user['id']])->count();
        if ($data) {
            foreach ($data as $item) {
                $idPool[] = $item['fromUid'];
            }
            $main = M('hongniang_love')->alias("l")->join("wx_" . $cid . "_user_weixin_info u ON l.uid = u.id")->where(['l.uid' => ['in', $idPool]])->field("l.*,u.nickname,u.headimgurl")->select();
            $return = [];
            foreach ((array)$main as $v) {
                $v['nickName'] = $v['nickname'];
                $v['photo'] = @json_decode($v['photo'], true);
                $v['age'] = date('Y') - date('Y', strtotime($v['birthday']));
                $return[] = $v;
            }
            Output::instance()->module('hn', "loveMe")->objArray($return, $count);
        } else {
            Output::instance()->resultCode(99, '没有记录');
        }
    }

    /*
     *互相关注的人
     */
    public function loveEach($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }

        $start = $params->start ?: 0;
        $limit = $params->limit ?: 10;

        $loveMe = M('hongniang_love_info')->where(['toUid' => $user['id']])->select();
        $iLove = M('hongniang_love_info')->where(['fromUid' => $user['id']])->select();
        $loveMePool = [];
        $iLovePool = [];
        foreach ((array)$loveMe as $v) {
            $loveMePool[] = $v['fromUid'];
        }
        foreach ((array)$iLove as $v) {
            $iLovePool[] = $v['toUid'];
        }
        $data = array_values(array_intersect($loveMePool, $iLovePool));
        if ($data) {
            $count = count($data);
            $data = array_slice($data, $start, $limit);
            $main = M('hongniang_love')->alias("l")->join("wx_" . $cid . "_user_weixin_info u ON l.uid = u.id")->where(['l.uid' => ['in', $data]])->field("l.*,u.nickname,u.headimgurl")->select();
            $handMe = M('hongninag_love_hand')->where(['toUid' => $user['id']])->select();
            $iHand = M('hongninag_love_hand')->where(['fromUid' => $user['id']])->select();
            $handMePool = [];
            $iHandPool = [];
            foreach ((array)$handMe as $v) {
                $handMePool[] = $v['fromUid'];
            }
            foreach ((array)$iHand as $v) {
                $iHandPool[] = $v['toUid'];
            }
            $return = [];
            foreach ((array)$main as $v) {
                $v['nickName'] = $v['nickname'];
                $v['photo'] = @json_decode($v['photo'], true);
                $v['age'] = date('Y') - date('Y', strtotime($v['birthday']));
                $v['handMe'] = in_array($v['uid'], $handMePool) ? 1 : 0;
                $v['Handit'] = in_array($v['uid'], $iHandPool) ? 1 : 0;
                $return[] = $v;
            }
            Output::instance()->module('hn', "loveMe")->objArray($return, $count);
        } else {
            Output::instance()->resultCode(99, '没有记录');
        }
    }

    /*
     * 喜欢别人接口
     * @params->uid 对方uid
     */
    public function doLove($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $templateModel = M('template_messages');
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $uid = intval($params->uid);
        if ($uid) {
            $main = M('hongniang_love')->where(['uid' => $user['id']])->find();
            $object = M('hongniang_love')->where(['uid' => $uid])->find();
            if ($main) {
                $check = M('hongniang_love_info')->where(['toUid' => $uid, 'fromUid' => $user['id']])->find();
                if ($check) {
                    Output::instance()->resultCode(96, '已经喜欢过TA了');
                    return;
                }
                $surplus = $main['surplus'];
                $dData = ['surplus' => $surplus - 1, 'love' => $main['love'] + 1];
                //相互喜欢判断
                $checkEach = M('hongniang_love_info')->where(['fromUid' => $uid, 'toUid' => $user['id']])->find();

                if ($surplus) {
                    if ($checkEach) {
                        $dData['loveEach'] = $main['loveEach'] + 1;
                        M('hongniang_love')->where(['uid' => $uid])->setInc('loveEach', 1);
                    }
                    M('hongniang_love')->where(['uid' => $user['id']])->save($dData);
                    $quota = M('hongniang_quota')->where(['uid' => $user['id'], 'status' => 0])->order(['id' => 'asc'])->find();
                    $quotaData = ['used' => $quota['used'] + 1];
                    if ($quota['quota'] - 1 == $quota['used']) {
                        $quota['status'] = 1;
                    }
                    M('hongniang_quota')->where(['id' => $quota['id']])->save($quotaData);
                    M('hongniang_love_info')->add(['fromUid' => $user['id'], 'toUid' => $uid, 'createTime' => date('Y-m-d H:i:s')]);

                    //给红娘钱

                    $configSql = M('hongniang_config')->where(['pk' => ['in', ['matchingCommission', 'rewardRatio', 'subRecommendedRewardRatio', 'recommendedRewardRatio']]])->select();
                    $config = [];
                    foreach ((array)$configSql as $cfg) {
                        $config[$cfg['pk']] = $cfg['value'];
                    }
                    $matchmakerInfo = M('hongniang_matchmaker')->where(['uid' => $main['refereeId']])->find();
                    if ($matchmakerInfo['id']) {
                        M('hongniang_earning')->add(['uid' => $main['refereeId'], 'cash' => $config['matchingCommission'] * $config['rewardRatio'], 'description' => $main['realname'] . '配对奖励', 'createTime' => date('Y-m-d H:i:s')]);
                        M('hongniang_matchmaker')->where(['uid' => $main['refereeId']])->setInc('earning', $config['matchingCommission'] * $config['rewardRatio']);
                        M('hongniang_matchmaker')->where(['uid' => $main['refereeId']])->setInc('balance', $config['matchingCommission'] * $config['rewardRatio']);
                    }
                    if ($matchmakerInfo['refereeId']) {
                        M('hongniang_earning')->add(['uid' => $matchmakerInfo['refereeId'], 'cash' => $config['matchingCommission'] * $config['recommendedRewardRatio'], 'description' => $main['realname'] . '配对奖励', 'createTime' => date('Y-m-d H:i:s')]);
                        M('hongniang_matchmaker')->where(['uid' => $matchmakerInfo['refereeId']])->setInc('earning', $config['matchingCommission'] * $config['recommendedRewardRatio']);
                        M('hongniang_matchmaker')->where(['uid' => $matchmakerInfo['refereeId']])->setInc('balance', $config['matchingCommission'] * $config['recommendedRewardRatio']);
                    }
                    if ($matchmakerInfo['refereeId2']) {
                        M('hongniang_earning')->add(['uid' => $matchmakerInfo['refereeId2'], 'cash' => $config['matchingCommission'] * $config['subRecommendedRewardRatio'], 'description' => $main['realname'] . '配对奖励', 'createTime' => date('Y-m-d H:i:s')]);
                        M('hongniang_matchmaker')->where(['uid' => $matchmakerInfo['refereeId2']])->setInc('earning', $config['matchingCommission'] * $config['subRecommendedRewardRatio']);
                        M('hongniang_matchmaker')->where(['uid' => $matchmakerInfo['refereeId2']])->setInc('balance', $config['matchingCommission'] * $config['subRecommendedRewardRatio']);
                    }

                    //发送模板消息
                    $msg = (date('Y') - date('Y', strtotime($main['birthday']))) . "岁，身高" . ($main['height']) . "CM，体重" . ($main['weight']) . "KG，" . ($this->educationMap[$main['education']] ? $this->educationMap[$main['education']] . '，' : '') . "年收入" . ($main['earning']) . "万，" . $main['province'] . $main['city'];
                    $templatemsg = $templateModel->where(['status' => 'hnPending'])->find();
                    $data['first'] = array('value' => '您有一个请求需要处理', 'color' => "#743A3A");
                    $data['keyword1'] = array('value' => '好友关注请求', 'color' => '#173177');
                    $data['keyword2'] = array('value' => $msg, 'color' => '#173177');
                    $data['keyword3'] = array('value' => date('Y-m-d H:i:s', time()), 'color' => '#173177');
                    $data['remark'] = array('value' => '点击打开详情处理', "color" => '#008000');
                    $template_id = $templatemsg['templateId'];
                    $url = C("SERVER_HOST") . "call.html?customerId=" . $cid . '&module=hn&method=index&params={"uid":' . $main['uid'] . "}#/loveIndex/" . $user['id'];//链接
                    $toUser = $object['openId'];//发送给谁（微信的openid）
                    $topcolor = "#FF0000";
                    Session::switchCustomer($cid);
                    WeixinApi::sendTpl($toUser, $template_id, $url, $topcolor, $data);
                    //结束
                    Output::instance()->resultCode(0, '喜欢成功');
                } else {
                    Output::instance()->resultCode(97, '没有配额了，请充值');
                }
            } else {
                Output::instance()->resultCode(98, '用户还没注册');
            }
        } else {
            Output::instance()->resultCode(99, '参数缺失');
        }
    }

    public function matchmakerIndex($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $matchmakerModel = M('hongniang_matchmaker')->where(['uid' => $user['id']])->find();
        if (!$matchmakerModel['id']) {
            $referee = M('hongniang_referee')->where(['uid' => $user['id']])->find();
            if ($referee['parentId']) {
                $referee2 = M('hongniang_referee')->where(['uid' => $referee['parentId']])->find();
            }
            $initData = [
                'uid' => $user['id'],
                'openId' => $openId,
                'refereeId' => $referee['parentId'] ?: 0,
                'refereeId2' => $referee2['parentId'] ?: 0,
                'createTime' => date('Y-m-d H:i:s'),
                'earning' => 0,
                'balance' => 0,
                'offer' => 0,
                'offerLoves' => 0,
                'qrcode' => ''
            ];
            $result = M('hongniang_matchmaker')->add($initData);
            $initData['id'] = $result;
            $initData['nickName'] = $user['nickname'];
            $initData['headimgurl'] = $user['headimgurl'];
            $matchmakerModel = $result ? $initData : [];
        } else {
            $matchmakerModel['nickName'] = $user['nickname'];
            $matchmakerModel['headimgurl'] = $user['headimgurl'];
        }
        if ($matchmakerModel) {
            Output::instance()->module('hn', "matchmaker")->object($matchmakerModel);
        } else {
            Output::instance()->resultCode(99, '初始化失败');
        }
    }

    public function getMatchmakerCondition($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $data = M('hongniang_matchmaker_condition')->where(['uid' => $user['id']])->find();
        if ($data) {
            $row = [];
            foreach ($data as $k => $v) {
                $row[$k] = $v ? $v : null;
            }
            $row['showMinAge'] = $row['maxAge'] ? date('Y') - $row['maxAge'] : null;
            $row['showMaxAge'] = $row['minAge'] ? date('Y') - $row['minAge'] : null;
            Output::instance()->module('hn', "condition")->object($row);
        } else {
            Output::instance()->resultCode(99, '未设置');
        }
    }

    public function matchmakerAccount($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }

        $start = $params->start ?: 0;
        $limit = $params->limit ?: 10;

        $info = M('hongniang_earning')->where(['uid' => $user['id']])->limit($start, $limit)->select();
        $count = M('hongniang_earning')->where(['uid' => $user['id']])->count();
        if ($info) {
            Output::instance()->module('hn', "matchmaker")->objArray($info, $count);
        } else {
            Output::instance()->resultCode(99, '没有收益记录');
        }
    }

    public function fromMatchmaker($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }

        $start = $params->start ?: 0;
        $limit = $params->limit ?: 10;

        $info = M('hongniang_love')->alias('l')->join("wx_" . $cid . "_user_weixin_info u ON l.uid = u.id")->where(['l.refereeId' => $user['id'], 'l.verify' => 1])->limit($start, $limit)->field("l.*,u.nickname,u.headimgurl")->select();
        $count = M('hongniang_love')->where(['refereeId' => $user['id'], 'verify' => 1])->count();
        if ($info) {
            $data = [];
            foreach ((array)$info as $v) {
                $v['photo'] = @json_decode($v['photo'], true);
                $v['age'] = date('Y') - date('Y', strtotime($v['birthday']));
                $data[] = $v;
            }
            Output::instance()->module('hn', "matchmaker")->objArray($data, $count);
        } else {
            Output::instance()->resultCode(99, '没有收益记录');
        }
    }

    public function unReg($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }

        $start = $params->start ?: 0;
        $limit = $params->limit ?: 10;

        $info = M('hongniang_referee')->alias('r')->join("wx_" . $cid . "_user_weixin_info u ON r.uid = u.id")->where(['r.reg' => 0, 'r.parentId' => $user['id']])->limit($start, $limit)->field("u.*")->select();
        $count = M('hongniang_referee')->where(['parentId' => $user['id'], 'reg' => 0])->count();
        if ($info) {
            Output::instance()->module('hn', "matchmaker")->objArray($info, $count);
        } else {
            Output::instance()->resultCode(99, '没有收益记录');
        }
    }

    /*
     * 设置发现条件
     */
    public function regMatchmakerCondition($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $minYear = date('Y') - intval($params->cmaxAge);
        $maxYear = date('Y') - intval($params->cminAge);
        $conditionModel = M('hongniang_matchmaker_condition');

        $conditionData = [
            'uid' => $user['id'],
            'openId' => $openId,
            'gender' => intval($params->cgender),
            'minAge' => $minYear,
            'maxAge' => $maxYear,
            'minHeight' => intval($params->cminHeight),
            'maxHeight' => intval($params->cmaxHeight),
            'minWeight' => intval($params->cminWeight),
            'maxWeight' => intval($params->cmaxWeight),
            'education' => intval($params->ceducation),
            'minEarning' => intval($params->cminEarning),
            'maxEarning' => intval($params->cmaxEarning),
            'province' => trim($params->cprovince),
            'city' => trim($params->ccity),
            'marital' => intval($params->cmarital)
        ];
        $check = $conditionModel->where(['uid' => $user['id']])->find();
        if ($check) {
            $conditionResult = $conditionModel->where(['uid' => $user['id']])->save($conditionData);
        } else {
            $conditionResult = $conditionModel->add($conditionData);
        }
        if ($conditionResult) {
            Output::instance()->resultCode(0, '写入成功');
        } else {
            Output::instance()->resultCode(1, '写入失败');
        }

    }

    /*
     * 提现
     * @params->money = 100.00
     */
    public function withdraw($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        if (intval($params->money) <= 0) {
            Output::instance()->resultCode(96, '参数有误，请输入正数');
            return;
        }

        $money = intval($params->money * 100) / 100;

        $surplus = M('hongniang_matchmaker')->where(['uid' => $user['id']])->find();
        if (!$surplus) {
            Output::instance()->resultCode(99, '红娘身份不存在');
            return;
        }
        if (intval($surplus['balance'] * 100) < ($money * 100)) {
            Output::instance()->resultCode(100, '余额不足');
            return;
        }

        $result = M('hongniang_withdraw')->add([
            'uid' => $user['id'],
            'openId' => $openId,
            'currentSurplus' => (intval($surplus['balance'] * 100) - ($money * 100)) / 100,
            'cash' => $money,
            'status' => 0,
            'createTime' => date('Y-m-d H:i:s'),
            'passTime' => ''
        ]);
        if ($result) {
            $update = M('hongniang_matchmaker')->where(['uid' => $user['id']])->save(['balance' => (intval($surplus['balance'] * 100) - ($money * 100)) / 100]);
            if ($update) {
                Output::instance()->resultCode(0, '申请成功，等待审核');
            } else {
                M('hongniang_withdraw')->where(['id' => $result])->delete();
                Output::instance()->resultCode(102, '申请失败');
            }
        } else {
            Output::instance()->resultCode(101, '申请失败');
        }
    }

    /*
     * 充值
     * @params->id = 3
     */
    public function recharge($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        if (intval($params->id) <= 0) {
            Output::instance()->resultCode(96, '参数有误，请输入正数');
            return;
        }

        $package = M('hongniang_package')->where(['id' => intval($params->id), 'status' => 1])->find();
        if (!$package) {
            Output::instance()->resultCode(97, '套餐不存在');
            return;
        }

        $money = $package['money'];
        $main = M('hongniang_love')->where(['uid' => $user['id']])->find();
        $ratio = 0;
        if ($main['agent']) {
            $agent = M('hongniang_agent')->where(['id' => $main['agent']])->find();
            $ratio = $agent['ratio'];
        }
        $data = [
            'uid' => $user['id'],
            'openId' => $openId,
            'channel' => 0,
            'amount' => $money,
            'num' => intval($package['num']),
            'ratio' => $ratio,
            'createTime' => date('Y-m-d H:i:s'),
            'close' => 0,
            'status' => 0
        ];
        $result = M('hongniang_income')->add($data);
        Session::switchCustomer($cid);
        if ($result) {
            Output::instance()->resultCode(0, [
                'module' => 'hn',
                'method' => 'rechargeCallback',
                'moduleId' => $result,
                'transportFee' => 0,
                'userName' => $openId,
                'desc' => '充值',
                'productFee' => $money
            ]);
        } else {
            Output::instance()->resultCode(99, '申请失败');
        }
    }

    /*
     * 充值回调
     * @params->id = 8
     */
    public function rechargeCallback($params)
    {
        $cid = Session::$user["customerId"];
        $openId = $params->userName;
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $id = intval($params->id);
        if (!$id) {
            Output::instance()->resultCode(96, '缺少关键ID');
            return;
        }

        $order = M('hongniang_income')->where(['id' => $id, 'status' => 0, 'close' => 0])->find();
        if (!$order) {
            Output::instance()->resultCode(97, '没有需要处理的充值');
            return;
        }
        $lover = M('hongniang_love')->where(['uid' => $user['id']])->find();
        $configSql = M('hongniang_config')->where(['pk' => ['in', ['registrationCommission', 'rewardRatio', 'subRecommendedRewardRatio', 'recommendedRewardRatio']]])->select();
        $config = [];
        foreach ((array)$configSql as $cfg) {
            $config[$cfg['pk']] = $cfg['value'];
        }
        $quota = $order['num'];
        $model = M('hongniang_income');
        $model->startTrans();
        try {
            M('hongniang_quota')->add(['uid' => $user['id'], 'openId' => $openId, 'quota' => $quota, 'used' => 0, 'money' => $order['amount'], 'status' => 0, 'createTime' => date('Y-m-d H:i:s'), 'endTime' => date('Y-m-d H:i:s', strtotime("+1 year"))]);
            M('hongniang_love')->where(['uid' => $user['id']])->save(['recharge' => $lover['recharge'] + $order['amount'], 'surplus' => $lover['surplus'] + $quota]);
            if (intval($lover['recharge']) === 0) {
                $matchmakerInfo = M('hongniang_matchmaker')->where(['uid' => $lover['refereeId']])->find();
                if ($matchmakerInfo['id']) {
                    M('hongniang_earning')->add(['uid' => $lover['refereeId'], 'cash' => $config['registrationCommission'] * $config['rewardRatio'], 'description' => $lover['realname'] . '注册奖励', 'createTime' => date('Y-m-d H:i:s')]);
                    M('hongniang_matchmaker')->where(['uid' => $lover['refereeId']])->setInc('earning', $config['registrationCommission'] * $config['rewardRatio']);
                    M('hongniang_matchmaker')->where(['uid' => $lover['refereeId']])->setInc('balance', $config['registrationCommission'] * $config['rewardRatio']);
                }
                if ($matchmakerInfo['refereeId']) {
                    M('hongniang_earning')->add(['uid' => $matchmakerInfo['refereeId'], 'cash' => $config['registrationCommission'] * $config['recommendedRewardRatio'], 'description' => $lover['realname'] . '注册奖励', 'createTime' => date('Y-m-d H:i:s')]);
                    M('hongniang_matchmaker')->where(['uid' => $matchmakerInfo['refereeId']])->setInc('earning', $config['registrationCommission'] * $config['recommendedRewardRatio']);
                    M('hongniang_matchmaker')->where(['uid' => $matchmakerInfo['refereeId']])->setInc('balance', $config['registrationCommission'] * $config['recommendedRewardRatio']);
                }
                if ($matchmakerInfo['refereeId2']) {
                    M('hongniang_earning')->add(['uid' => $matchmakerInfo['refereeId2'], 'cash' => $config['registrationCommission'] * $config['subRecommendedRewardRatio'], 'description' => $lover['realname'] . '注册奖励', 'createTime' => date('Y-m-d H:i:s')]);
                    M('hongniang_matchmaker')->where(['uid' => $matchmakerInfo['refereeId2']])->setInc('earning', $config['registrationCommission'] * $config['subRecommendedRewardRatio']);
                    M('hongniang_matchmaker')->where(['uid' => $matchmakerInfo['refereeId2']])->setInc('balance', $config['registrationCommission'] * $config['subRecommendedRewardRatio']);
                }
            }
            $model->where(['id' => $id])->save(['status' => 1]);
            $model->commit();
        } catch (Exception $e) {
            $model->rollback();
        }
        Session::switchCustomer($cid);
    }

    public function discover($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $configModel = M('hongniang_config')->where(['pk' => 'discoverRecommendedNumber'])->find();
        $number = $configModel ? intval($configModel['value']) : 5;

        $self = M('hongniang_love')->where(['uid' => $user['id']])->find();
        $targetGender = $self['gender'] == 2 ? 1 : 2;
        $c = M('hongniang_condition')->where(['uid' => $user['id']])->find();

        $today = M('hongniang_discover')->where(['uid' => $user['id'], 'dateline' => date('Y-m-d')])->select();
        if (count($today) !== 0) {
            $pool = [];
            foreach ($today as $v) {
                $pool[] = $v['eUid'];
            }
            $main = M('hongniang_love')->alias("l")->join("wx_" . $cid . "_user_weixin_info u ON l.uid = u.id")->where(['l.uid' => ['in', $pool], 'l.verify' => 1, 'l.gender' => $targetGender])->field("l.*,u.nickname,u.headimgurl")->select();
            $condition = M('hongniang_condition')->where(['uid' => ['in', $pool]])->select();
            $conditionPool = [];
            foreach ((array)$condition as $v) {
                $conditionPool[$v['uid']] = $v;
            }
            $return = [];
            foreach ((array)$main as $v) {
                $loveIt = M('hongniang_love_info')->where(['fromUid' => $user['id'], 'toUid' => $v['uid']])->find();
                $v['nickName'] = $v['nickname'];
                $v['photo'] = @json_decode($v['photo'], true);
                $v['age'] = date('Y') - date('Y', strtotime($v['birthday']));
                $v['condition'] = $conditionPool[$v['uid']] ?: [];
                $v['loveIt'] = $loveIt ? 1 : 0;
                $return[] = $v;
            }
            Output::instance()->module('hn', "discover")->objArray($return);
        } else {
            $condition = [];
            if ($c['marital']) {
                $condition['marital'] = $c['marital'] == 1 ? 1 : ['egt', 2];
            }
            if ($c['province'] && $c['city']) {
                $condition['province'] = $c['province'];
                $condition['city'] = $c['city'];
            }
            if ($c['minEarning']) {
                $condition['earning'] = ['egt', $c['minEarning']];
            }
            if ($c['maxEarning']) {
                $condition['earning'] = ['elt', $c['maxEarning']];
            }
            if ($c['education']) {
                $condition['education'] = ['egt', $c['education']];
            }
            if ($c['maxWeight']) {
                $condition['weight'] = ['elt', $c['maxWeight']];
            }
            if ($c['minWeight']) {
                $condition['weight'] = ['egt', $c['minWeight']];
            }
            if ($c['maxHeight']) {
                $condition['height'] = ['elt', $c['maxHeight']];
            }
            if ($c['minHeight']) {
                $condition['height'] = ['egt', $c['minHeight']];
            }
            if ($c['minAge']) {
                $condition['birthday'] = ['egt', $c['minAge'] . '-01-01'];
            }
            if ($c['maxAge']) {
                $condition['birthday'] = ['elt', $c['maxAge'] . '-01-01'];
            }
            $return = [];
            $extPool = [];
            $had = M('hongniang_discover')->where(['uid' => $user['id']])->select();
            foreach ((array)$had as $v) {
                $extPool[] = intval($v['eUid']);
            }
            $extPool[] = intval($user['id']);
            $extCondition['l.uid'] = ['not in', $extPool];
            $extCondition['l.verify'] = 1;
            $extCondition['l.gender'] = $targetGender;
            $main = (array_filter(self::discoverSearch($cid, $number, $condition, $extCondition)));
            if (count($main) > $number) {
                $main = array_slice($main, 0, $number);
            }

            foreach ((array)$main as $v) {
                $ids[] = ['uid' => $user['id'], 'eUid' => $v['uid'], 'dateline' => date('Y-m-d')];
                $loveIt = M('hongniang_love_info')->where(['fromUid' => $user['id'], 'toUid' => $v['uid']])->find();
                $v['nickName'] = $v['nickname'];
                $v['photo'] = @json_decode($v['photo'], true);
                $v['age'] = date('Y') - date('Y', strtotime($v['birthday']));
//                $v['condition'] = M('hongniang_condition')->where(['uid' => $v['uid']])->find() ?: [];
                $v['loveIt'] = $loveIt ? 1 : 0;
                $return[] = $v;
            }
            M('hongniang_discover')->addAll($ids);
            Output::instance()->module('hn', "discover")->objArray($return);
        }
    }

    public static function discoverSearch($cid, $number, $condition, $extCondition, $return = [])
    {
        $main = M('hongniang_love')->alias("l")->join("wx_" . $cid . "_user_weixin_info u ON l.uid = u.id")->where($condition)->where($extCondition)->field("l.*,u.nickname,u.headimgurl")->limit(0, $number)->select();
        $return = array_merge((array)$main, (array)$return);
        if (count($main) < $number) {
            if (count($condition) > 1) {
                array_shift($condition);
                return self::discoverSearch($cid, $number - count($main), $condition, $extCondition, $return);
            }
        }
        return $return;
    }

    public function matchmakerDiscover($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $configModel = M('hongniang_config')->where(['pk' => 'discoverRecommendedNumber'])->find();
        $number = $configModel ? intval($configModel['value']) : 5;


        $c = M('hongniang_matchmaker_condition')->where(['uid' => $user['id']])->find();

        $today = M('hongniang_matchmaker_discover')->where(['uid' => $user['id'], 'dateline' => date('Y-m-d')])->select();
        if (count($today) !== 0) {
            $pool = [];
            foreach ($today as $v) {
                $pool[] = $v['eUid'];
            }
            $main = M('hongniang_love')->alias("l")->join("wx_" . $cid . "_user_weixin_info u ON l.uid = u.id")->where(['l.uid' => ['in', $pool], 'l.verify' => 1])->field("l.*,u.nickname,u.headimgurl")->select();
            $condition = M('hongniang_condition')->where(['uid' => ['in', $pool]])->select();
            $conditionPool = [];
            foreach ((array)$condition as $v) {
                $conditionPool[$v['uid']] = $v;
            }
            $return = [];
            foreach ((array)$main as $v) {
                $loveIt = M('hongniang_love_info')->where(['fromUid' => $user['id'], 'toUid' => $v['uid']])->find();
                $v['nickName'] = $v['nickname'];
                $v['photo'] = @json_decode($v['photo'], true);
                $v['age'] = date('Y') - date('Y', strtotime($v['birthday']));
                $v['condition'] = $conditionPool[$v['uid']] ?: [];
                $v['loveIt'] = $loveIt ? 1 : 0;
                $return[] = $v;
            }
            Output::instance()->module('hn', "discover")->objArray($return);
        } else {
            $condition = [];
            if ($c['marital']) {
                $condition['marital'] = $c['marital'] == 1 ? 1 : ['egt', 2];
            }
            if ($c['province'] && $c['city']) {
                $condition['province'] = $c['province'];
                $condition['city'] = $c['city'];
            }
            if ($c['minEarning']) {
                $condition['earning'] = ['egt', $c['minEarning']];
            }
            if ($c['maxEarning']) {
                $condition['earning'] = ['elt', $c['maxEarning']];
            }
            if ($c['education']) {
                $condition['education'] = ['egt', $c['education']];
            }
            if ($c['maxWeight']) {
                $condition['weight'] = ['elt', $c['maxWeight']];
            }
            if ($c['minWeight']) {
                $condition['weight'] = ['egt', $c['minWeight']];
            }
            if ($c['maxHeight']) {
                $condition['height'] = ['elt', $c['maxHeight']];
            }
            if ($c['minHeight']) {
                $condition['height'] = ['egt', $c['minHeight']];
            }
            if ($c['minAge']) {
                $condition['birthday'] = ['egt', $c['minAge'] . '-01-01'];
            }
            if ($c['maxAge']) {
                $condition['birthday'] = ['elt', $c['maxAge'] . '-01-01'];
            }
            if ($c['gender']) {
                $condition['gender'] = $c['gender'];
            }
            $return = [];
            $extPool = [];
            $had = M('hongniang_matchmaker_discover')->where(['uid' => $user['id']])->select();
            foreach ((array)$had as $v) {
                $extPool[] = intval($v['eUid']);
            }
            $extPool[] = intval($user['id']);
            $extCondition['l.uid'] = ['not in', $extPool];
            $extCondition['l.verify'] = 1;
            $main = (array_filter(self::discoverSearch($cid, $number, $condition, $extCondition)));
            if (count($main) > $number) {
                $main = array_slice($main, 0, $number);
            }
            foreach ((array)$main as $v) {
                $ids[] = ['uid' => $user['id'], 'eUid' => $v['uid'], 'dateline' => date('Y-m-d')];
                $loveIt = M('hongniang_love_info')->where(['fromUid' => $user['id'], 'toUid' => $v['uid']])->find();
                $v['nickName'] = $v['nickname'];
                $v['photo'] = @json_decode($v['photo'], true);
                $v['age'] = date('Y') - date('Y', strtotime($v['birthday']));
                $v['condition'] = M('hongniang_condition')->where(['uid' => $v['uid']])->find() ?: [];
                $v['loveIt'] = $loveIt ? 1 : 0;
                $return[] = $v;
            }

            M('hongniang_matchmaker_discover')->addAll($ids);
            Output::instance()->module('hn', "discover")->objArray($return);
        }
    }

    /*
     * 个人首页-基本资料
     * @params->uid 传来对方的uid
     */
    public function loveIndex($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }

        $loveID = intval($params->uid);

        $info = M('hongniang_love')->where(['uid' => $loveID])->find();
        $loveIt = M('hongniang_love_info')->where(['fromUid' => $user['id'], 'toUid' => $loveID])->find();
        $loveMe = M('hongniang_love_info')->where(['fromUid' => $loveID, 'toUid' => $user['id']])->find();
        if ($info['success'] == 0) {
            $handIt = M('hongniang_love_hand')->where(['fromUid' => $user['id'], 'toUid' => $loveID])->find();
            $handMe = M('hongniang_love_hand')->where(['fromUid' => $loveID, 'toUid' => $user['id']])->find();
        }

        if ($info) {
            $weixinInfo = $userModel->where(['id' => $loveID])->find();
            $info['nickName'] = $weixinInfo['nickname'];
            $info['headimgurl'] = $weixinInfo['headimgurl'];
            $info['photo'] = @json_decode($info['photo'], true);
            $info['age'] = date('Y') - date('Y', strtotime($info['birthday']));
            $condition = M('hongniang_condition')->where(['uid' => $loveID])->find();
            if ($condition) {
                foreach ($condition as $key => $value) {
                    if (!$value) {
                        $condition[$key] = null;
                    }
                }
                $condition['maxAge'] ? $condition['showMinAge'] = date('Y') - $condition['maxAge'] : "";
                $condition['minAge'] ? $condition['showMaxAge'] = date('Y') - $condition['minAge'] : "";
            }
            $info['condition'] = $condition ?: [];
            $info['loveIt'] = $loveIt ? 1 : 0;
            $info['loveMe'] = $loveMe ? 1 : 0;
            $info['handMe'] = $handMe ? 1 : 0;
            $info['handIt'] = $handIt ? 1 : 0;
            Output::instance()->module('hn', "loveIndex")->object($info);
        } else {
            Output::instance()->resultCode(99, '用户资料不存在');
        }
    }

    /*
     * 请求牵手接口
     * @params->uid 对方uid
     */
    public function doHand($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer($cid);
        $templateModel = M('template_messages');
        $userModel = M('user_weixin_info');
        Session::switchCustomer(0);
        $user = $userModel->where(['openid' => $openId])->find();
        if (!$user) {
            Output::instance()->resultCode(code_user_not_exist);
            return;
        }
        $uid = intval($params->uid);
        if ($uid) {
            $main = M('hongniang_love')->where(['uid' => $user['id']])->find();
            $object = M('hongniang_love')->where(['uid' => $uid])->find();
            if ($main) {
                if ($main['success'] == 1) {
                    Output::instance()->resultCode(95, '你已经和别人牵手啦');
                    return;
                }

                $check = M('hongniang_love_hand')->where(['toUid' => $uid, 'fromUid' => $user['id']])->find();
                if ($check) {
                    Output::instance()->resultCode(96, '已经发送过牵手请求了');
                    return;
                }

                M('hongniang_love_hand')->add(['fromUid' => $user['id'], 'toUid' => $uid, 'createTime' => date('Y-m-d H:i:s')]);

                //相互判断
                $checkEach = M('hongniang_love_hand')->where(['fromUid' => $uid, 'toUid' => $user['id']])->find();
                if ($checkEach) {
                    $configSql = M('hongniang_config')->where(['pk' => ['in', ['successCommission', 'rewardRatio', 'subRecommendedRewardRatio', 'recommendedRewardRatio']]])->select();
                    $config = [];
                    foreach ((array)$configSql as $cfg) {
                        $config[$cfg['pk']] = $cfg['value'];
                    }
                    M('hongniang_love')->where(['uid' => $uid])->save(['success' => 1, 'loveId' => $user['id']]);
                    M('hongniang_love')->where(['uid' => $user['id']])->save(['success' => 1, 'loveId' => $uid]);
                    $matchmakerInfo = M('hongniang_matchmaker')->where(['uid' => $main['refereeId']])->find();
                    if ($matchmakerInfo['id']) {
                        M('hongniang_earning')->add(['uid' => $main['refereeId'], 'cash' => $config['successCommission'] * $config['rewardRatio'], 'description' => $main['realname'] . '配对成功奖励', 'createTime' => date('Y-m-d H:i:s')]);
                        M('hongniang_matchmaker')->where(['uid' => $main['refereeId']])->setInc('earning', $config['successCommission'] * $config['rewardRatio']);
                        M('hongniang_matchmaker')->where(['uid' => $main['refereeId']])->setInc('balance', $config['successCommission'] * $config['rewardRatio']);
                    }
                    if ($matchmakerInfo['refereeId']) {
                        M('hongniang_earning')->add(['uid' => $matchmakerInfo['refereeId'], 'cash' => $config['successCommission'] * $config['recommendedRewardRatio'], 'description' => $main['realname'] . '配对成功奖励', 'createTime' => date('Y-m-d H:i:s')]);
                        M('hongniang_matchmaker')->where(['uid' => $matchmakerInfo['refereeId']])->setInc('earning', $config['successCommission'] * $config['recommendedRewardRatio']);
                        M('hongniang_matchmaker')->where(['uid' => $matchmakerInfo['refereeId']])->setInc('balance', $config['successCommission'] * $config['recommendedRewardRatio']);
                    }
                    if ($matchmakerInfo['refereeId2']) {
                        M('hongniang_earning')->add(['uid' => $matchmakerInfo['refereeId2'], 'cash' => $config['successCommission'] * $config['subRecommendedRewardRatio'], 'description' => $main['realname'] . '配对成功奖励', 'createTime' => date('Y-m-d H:i:s')]);
                        M('hongniang_matchmaker')->where(['uid' => $matchmakerInfo['refereeId2']])->setInc('earning', $config['successCommission'] * $config['subRecommendedRewardRatio']);
                        M('hongniang_matchmaker')->where(['uid' => $matchmakerInfo['refereeId2']])->setInc('balance', $config['successCommission'] * $config['subRecommendedRewardRatio']);
                    }
                    Output::instance()->resultCode(0, '配对成功');
                    return;
                }
                //判断结束
                //发送模板消息
                $templatemsg = $templateModel->where(['status' => 'hnPending'])->find();
                $data['first'] = array('value' => '您有一个请求需要处理', 'color' => "#743A3A");
                $data['keyword1'] = array('value' => '牵手请求', 'color' => '#173177');
                $data['keyword2'] = array('value' => $main['realname'], 'color' => '#173177');
                $data['keyword3'] = array('value' => date('Y-m-d H:i:s', time()), 'color' => '#173177');
                $data['remark'] = array('value' => '点击打开详情处理', "color" => '#008000');
                $template_id = $templatemsg['templateId'];
                $url = C("SERVER_HOST") . "call.html?customerId=" . $cid . '&module=hn&method=loveIndex&params={"uid":' . $main['uid'] . '}#/pindex/0';//链接
                $toUser = $object['openId'];//发送给谁（微信的openid）
                $topcolor = "#FF0000";
                WeixinApi::sendTpl($toUser, $template_id, $url, $topcolor, $data);
                //结束
                Output::instance()->resultCode(0, '请求成功，等待对方回应');

            } else {
                Output::instance()->resultCode(98, '用户还没注册');
            }
        } else {
            Output::instance()->resultCode(99, '参数缺失');
        }
    }

    public function packageList($params)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $openId = Session::$user["userName"];
        Session::switchCustomer(0);
        $data = M('hongniang_package')->where(['status' => 1])->select();
        if ($data) {
            Output::instance()->module('hn', "package")->object($data);
        } else {
            Output::instance()->module('hn', "package")->object([]);
        }
    }


}
